#!/usr/local/bin/php
<?php
require_once 'common.php';

/* @var $logger Log */
global $logger;
/* @var $appPayServerTable OpTableModel */
global $appPayServerTable;
/* @var $appPayServerValidTable OpTableModel */
global $appPayServerValidTable;

$options = getopt('a:g:e:');
if (empty($options)) {
    $logger->err("usage: " . basename(__FILE__) . " [-a import|delete] -g app_id -e environment");
    exit();
}
if (isset($options['a'])) {
    $action = $options['a'];
} else {
    $action = 'import';
}
if (!in_array($action, array('import', 'delete'))) {
    $logger->err("wrong action");
    exit();
}
if (isset($options['g'])) {
    $companyId = $options['g'];
} else {
    $logger->err("no app specified");
    exit();
}
if (isset($options['e']) && in_array($options['e'], array(OaAppModel::APP_CONFIG_ENV_TEST, 
	OaAppModel::APP_CONFIG_ENV_PRODUCTION))) {
	$env = $options['e'];
} else {
    $logger->err("no environment specified");
    exit();
}

if ($action == 'import') {
	if (!importPayServer($companyId, $env, $message)) {
		$logger->warning($message);
		continue;
	}
	$logger->info("import pay server ok: app_id-$companyId, env-$env");
} else if ($action == 'delete') {
	$payServers = $appPayServerTable->get(array(
		'app_id' => $companyId, 
		'environment' => $env
	));
	foreach ($payServers as $payServer) {
		if (!$appPayServerValidTable->delete(array(
			'pay_server_id' => $payServer['id']
		))) {
			$logger->warning("delete from pay server valid table failed");
			continue;
		}
		if (!$appPayServerTable->delete(array(
			'id' => $payServer['id']
		))) {
			$logger->warning("delete from pay server table failed");
			continue;
		}
	}
	$logger->info("delete pay server ok: app_id-$companyId, env-$env");
}
